package com.ruoyi.task.service.impl;

import com.ruoyi.common.core.domain.ServiceResponse;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.task.domain.ModelParams;
import com.ruoyi.task.domain.SubBankServerConfig;
import com.ruoyi.task.mapper.SubBankServerConfigMapper;
import com.ruoyi.task.service.IPromptService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

@Service
public class PromptServiceImpl implements IPromptService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SubBankServerConfigMapper subBankServerConfigMapper;

    @Override
    public List<SubBankServerConfig> queryBranchBankConfigList() {
        return subBankServerConfigMapper.queryBranchBankServerConfigList();
    }

    @Override
    public String uploadFile(List<MultipartFile> files, String branchBank) {
        try {

            MultiValueMap<String, Object> linkedMultiValueMap = new LinkedMultiValueMap();

            for (MultipartFile file : files) {
                try {
                    ByteArrayResource resource = new ByteArrayResource(file.getBytes()) {
                        @Override
                        public String getFilename() {
                            return file.getOriginalFilename();
                        }
                    };
                    linkedMultiValueMap.add("files", resource);
                } catch (IOException e) {
                    logger.error("读取文件失败", e);
                    throw new ServiceException("读取文件失败");
                }
            }


            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity(
                    linkedMultiValueMap, (MultiValueMap) headers);

            // 根据分行标识，获取相应配置的IP
            String ip = queryBranchBankIp(branchBank);
            String uploadUrl = "http://" + ip + ":8081/ai/uploadFile";
            logger.info("upload file uploadUrl:{}", uploadUrl);

            RestTemplate restTemplate = getRestTemplate();

            ResponseEntity<ServiceResponse> response = restTemplate.exchange(uploadUrl,
                    HttpMethod.POST,
                    requestEntity, ServiceResponse.class, new Object[0]);
            String code = ((ServiceResponse) Objects.<Object>requireNonNull(
                    response.getBody())).getCode();
            logger.info("upload file result code:{}", code);
            if (!"0".equals(code)) {
                String msg = ((ServiceResponse) Objects.<Object>requireNonNull(
                        response.getBody())).getMsg();
                logger.info("upload file result msg:{}", msg);
                throw new ServiceException(msg);
            }
            String data = (String) ((ServiceResponse) Objects.<Object>requireNonNull(
                    response.getBody())).getData();
            logger.info("upload file result fileId:{}", data);

            return data;
        }catch (ServiceException e){
            throw e;
        } catch (Exception e) {
            logger.error("upload file error", e);
            throw new ServiceException("文件上传失败");
        }
    }



    @Override
    public String requestModel(ModelParams modelParams) {
        try {
            // 根据分行标识，获取相应配置的IP
            String ip = queryBranchBankIp(modelParams.getBranchBank());
            String url = "http://" + ip + ":8081/ai/aiModel";
            logger.info("requestModel ai Url:{}", url);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<ModelParams> requestEntity = new HttpEntity<>(modelParams, headers);

            RestTemplate restTemplate = getRestTemplate();

            ResponseEntity<ServiceResponse> response = restTemplate.exchange(url,
                    HttpMethod.POST,
                    requestEntity, ServiceResponse.class);
            String code = ((ServiceResponse) Objects.<Object>requireNonNull(
                    response.getBody())).getCode();
            logger.info("requestModel result code:{}", code);
            if (!"0".equals(code)) {
                String msg = ((ServiceResponse) Objects.<Object>requireNonNull(
                        response.getBody())).getMsg();
                logger.info("requestModel result msg:{}", msg);
                throw new ServiceException(msg);
            }
            String data = (String) ((ServiceResponse) Objects.<Object>requireNonNull(
                    response.getBody())).getData();
            logger.info("requestModel result:{}", data);

            return data;
        } catch (Exception e) {
            logger.error("requestModel error", e);
            throw new ServiceException("请求模型失败");
        }
    }


    /**
     * 根据分行标识，查询IP
     * @param branchBank
     * @return
     */
    private String queryBranchBankIp(String branchBank) {
        try {
            // 查询数据库配置IP
            SubBankServerConfig serverConfig = subBankServerConfigMapper.queryBranchBankServerIp(
                    branchBank);
            if (serverConfig == null) {
                throw new ServiceException("未获取到相应分行的IP，请确认是否有配置");
            }

            return serverConfig.getServerIp();
        } catch (Exception e) {
            logger.error("request model error", e);
            throw new ServiceException("未获取到相应分行的IP，请确认是否有配置");
        }
    }


    /**
     * 获取RestTemplate实例
     *
     * @return RestTemplate实例
     */
    private static RestTemplate getRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        // 设置连接和读取超时时间（以毫秒为单位）
        int connectTimeout = 5000; // 连接超时时间
        int readTimeout = 120000;    // 读取超时时间

        // 获取当前的请求工厂并配置超时
        if (restTemplate.getRequestFactory() instanceof SimpleClientHttpRequestFactory) {
            SimpleClientHttpRequestFactory factory = (SimpleClientHttpRequestFactory) restTemplate.getRequestFactory();
            factory.setConnectTimeout(connectTimeout);
            factory.setReadTimeout(readTimeout);
            restTemplate.setRequestFactory(factory);
        } else {
            // 如果使用的是其他类型的请求工厂，例如 HttpComponentsClientHttpRequestFactory，则需要单独配置
            SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
            factory.setConnectTimeout(connectTimeout);
            factory.setReadTimeout(readTimeout);
            restTemplate.setRequestFactory(factory);
        }
        return restTemplate;
    }
}
